class_name SellPortal
extends Node2D

@export var unit_pool: UnitPool
@export var player_stats: PlayerStats

@onready var gold_display: HBoxContainer = %GoldDisplay
@onready var count: Label = $UI/GoldDisplay/Count
@onready var hover_area: Area2D = %HoverArea
@onready var outline_highlighter: OutlineHighlighter = %OutlineHighlighter

var current_unit: Unit


func _ready() -> void:
	hover_area.area_entered.connect(_on_area_entered)
	hover_area.area_exited.connect(_on_area_exited)


func setup_unit(unit: Unit) -> void:
	unit.drag_and_drop.dropped.connect(_on_unit_dropped.bind(unit))
	unit.quick_sell_pressed.connect(_sell_unit.bind(unit))


func _sell_unit(unit: Unit) -> void:
	player_stats.gold += unit.stats.get_gold_value()
	# TODO give items back to item pool
	unit_pool.add_unit(unit.stats)
	
	unit.queue_free()


func _on_unit_dropped(_starting_position: Vector2, unit: Unit) -> void:
	if unit and unit == current_unit:
		_sell_unit(unit)


func _on_area_entered(area: Area2D) -> void:
	var unit := area.get_parent().get_parent()
	current_unit = unit
	count.text = str(unit.stats.get_gold_value())
	outline_highlighter.highlight()
	gold_display.show()


func _on_area_exited(area: Area2D) -> void:
	var unit := area.get_parent().get_parent()
	if unit and unit == current_unit:
		current_unit = null
	
	outline_highlighter.clear_highlight()
	gold_display.hide()
